import { get, post } from './http'
import { random } from '_commonFn/number'
import md5 from 'md5'
import { failTextVantToa, loadingVantToa, clearVantToa } from "_projectFn/prompt"
import { saveLoginInfo, delLoginUserInfo } from "_projectFn/login"
import Router from '_router/router'
import { getCookie } from '_commonFn/cookie'
import { getQueryStr } from '../utils/common/url'
import { isLoginChose } from "_projectFn/login" 
import { getLog } from "_projectFn/info" 
import { dataURLtoBlob } from '_commonFn/image'
import { getText } from '../utils/common/string'

// 获取广告List
export const getAds = () => get({url: 'GetCarousel'})

export function commonRequestData({
    apiName,
    requestData,
    timeout = 10000,
    taskId = "",
    headers
}) {
    const data = {
        ApiOuterName: apiName,
        RequestBody: requestData,
        TimeStamp: new Date().getTime(),
        Nonce: md5(String(random(0, 3000))),
        ApiKey: 'All'
    }
    // const key = `${data.ApiKey}${data.ApiOuterName}${data.RequestBody ? JSON.stringify(data.RequestBody) : ''}${data.TimeStamp}${data.Nonce}`.trim()
    // console.log('key', key)
    data.Sign = md5(`${data.ApiKey}${data.ApiOuterName}${data.RequestBody ? JSON.stringify(data.RequestBody) : ''}${data.TimeStamp}${data.Nonce}`.trim()).toUpperCase()
    return post({
        url: `/Gateway`,
        taskId,
        params: data,
    })
}

// 获取区域列表
export const getAreaList = ({code = 1, taskId = `getAreaList/${code}`, callback, isLoad = true}) => {
    if (typeof callback === 'function') {
        if (isLoad) loadingVantToa({})
        get({
            url: `api/v1/getAreaList/${code}`,
            taskId
        })
        .then(res => {
            // console.log('获取区域列表 res：', res)
            if (res.errcode == 1000) {
                clearVantToa()
                typeof callback === 'function' && callback(res.data)
            } else {
                if (res.errcode != -2 && res.errCode != 1100) {
                    failTextVantToa()
                } else {
                    clearVantToa()
                }
            }
        }, res => {
            console.log('fail: res', res)
            if (res.errcode != 2000) {
                failTextVantToa()
            }
        })
        .catch(res => {
            console.log('catch：res', res)
            failTextVantToa()
        })
    } else {
        return get({
            url: `api/v1/getAreaList/${code}`,
            taskId
        })
    }
}

// 获取用户业务信息
export const getUserBusInfo = ({
    userId,
    taskId = userId
}) => {
    // console.log('userId', userId)
    if (userId) {
        return commonRequestData({
            apiName: 'UserIndex_MyBusiness',
            requestData: {
                UserId: userId,
            },
            taskId
        })
    }
    return Promise.reject({errCode: 2001})
}

// 执行关注
export const toFollow = ({userId, callback}) => {
    loadingVantToa({})
    commonRequestData({
        apiName: `UserFunsUser`,
        requestData: {
            FunsUserId: userId
        }
    })
    .then(res => {
        console.log('关注用户 res：', res)
        if (res.errcode == 0) {
            clearVantToa()
            typeof callback === 'function' && callback(true)
        } else {
            if (res.errcode != -2 && res.errCode != 1100) {
                failTextVantToa()
            } else {
                clearVantToa()
            }
        }
    }, res => {
        console.log('fail: res', res)
        if (res.errcode != 2000) {
            failTextVantToa()
        }
    })
    .catch(res => {
        console.log('catch：res', res)
        failTextVantToa()
    })
}

// 执行取消关注
export const toCancelFollow = ({userId, callback}) => {
    loadingVantToa({})
    commonRequestData({
        apiName: `UserFunsCancel`,
        requestData: {
            CancelType: 'User',
            CanCelObject: userId
        }
    })
    .then(res => {
        console.log('取消关注用户 res：', res)
        if (res.errcode == 0) {
            clearVantToa()
            typeof callback === 'function' && callback(true)
        } else {
            if (res.errcode != -2 && res.errCode != 1100) {
                failTextVantToa(res.message)
            } else {
                clearVantToa()
            }
        }
    }, res => {
        console.log('fail: res', res)
        if (res.errcode != 2000) {
            failTextVantToa()
        }
    })
    .catch(res => {
        console.log('catch：res', res)
        failTextVantToa()
    })
}

// 账号密码登录接口
export const accountLogin = ({account, password}) => {
    loadingVantToa({})
    console.log('account', account)
    console.log('password', password)
    const code = account + '-' + md5(password + 'CEAE206667421F9A6C3C93EE14039455').toUpperCase().toUpperCase()
    get({
        url: `api/v1/setLoginPwd/${code}`,
        taskId: 'setLoginPwd',
    })
    .then(res => {
        console.log('账号密码登录 res：', res)
        if (res.errcode == 1000) {
            saveLoginInfo(res.data) // 保存用户信息
            clearVantToa()
            const enterUrl = decodeURIComponent(getQueryStr().to)
            if (enterUrl) {
                const url = enterUrl.replace(location.origin, '').split('&code=')[0]
                // console.log('要跳转的URL', url)
                window.location.href = url
            } else {
                if (window.history.length) {
                    Router.go(-1)
                } else {
                    if (process.env.IS_LOCAL) {
                        Router.push({
                            name: 'Home',
                            path: ''
                        })
                    } else {
                        window.location.href = '../index.html'
                    }
                }
            }
        } else {
            failTextVantToa(res.message)
        }
    }, res => {
        console.log('fail: res', res)
        if(res.errcode != 2000){
            failTextVantToa('服务器正在修整')
        }
    })
    .catch(res => {
        console.log('catch：res', res)
        failTextVantToa('服务器正在修整，请稍后')
    })
}

//检测是否下线，如果则清除所有cookie
export const isLogined = ({callback}) => {
    const ticket = getCookie('Ticket')
    if (ticket) { // 如果设置了cookie,则执行检测
        let isLoginedBool = false
        post({
            url: '/api/v1/VerifyUser',
            params: { 'Ticket': ticket }
        })
        .then(res => {
            console.log('检测登录 res', res)
            if (res.errcode == 1000) {
                isLoginedBool = true
            } else {
                delLoginUserInfo() // 执行清除登录用户信息
            }
        }, res => {
            console.log('fail: res', res)
        })
        .catch(res => {
            console.log('catch：res', res)
        })
        .finally(() => {
            const isCallbackFn = typeof callback === 'function'
            if (isLoginedBool && isCallbackFn === false) {
                // 执行页面返回
                Router.go(-1)
            }
            typeof callback === 'function' && callback(isLoginedBool)
        })
    } else {
        delLoginUserInfo() // 执行清除登录用户信息
        typeof callback === 'function' && callback(false)
    }
}

// 获取微信SDK数据
export const getWechatSDK = (url = /(Android)/i.test(navigator.userAgent) ? location.href.split('#')[0] : window.entryUrl) => {
    // console.log('url', url)
    return get({
        url: '/api/v1/getJsapi',
        params: {
            "Url": url
            // "Url": decodeURIComponent(`${process.env.BASE_URL}/app/`)
        }
    })
}

// 获取用户的主页信息
export const getUserIndex = (userId) => {
    if (userId) {
        return commonRequestData({
            apiName: 'UserIndex',
            requestData: {
                UserId: userId
            }
        })
    }
    return Promise.reject({
        errCode: 2000,
        data: {}
    })
}

// 获取获取支付基本信息接口
export const getPayConfigBasicApi = () => {
    return get({
        url: 'GetPayConfig',
    })
}

// 获取免密支付范围
export const freePwdCount = () => {
    return get({
        url: 'GetFreesecret',
    }) 
}

// 获取支付所有信息
export const getPayConfig = ({callback = ''}) => {
    if(typeof callback === 'function'){
        loadingVantToa({})
        Promise.all([getPayConfigBasicApi(), freePwdCount()])
        .then(res => {
            // console.log('获取支付所有信息 res：', res)
            if (res[0].errcode == 1000 && res[1].errcode ) {
                clearVantToa()
                callback({
                    ...res[0].data,
                    ...res[1].data
                })
                // callback({
                //     ...res[0].data,
                //     Freesecret: 1,
                // })
            } else {
                if (res.errcode != -2 && res.errCode != 1100) {
                    failTextVantToa()
                } else {
                    clearVantToa()
                }
            }
        }, res => {
            console.log('fail: res', res)
            if (res.errcode != 2000) {
                failTextVantToa()
            }
        })
        .catch(res => {
            console.log('catch：res', res)
            failTextVantToa()
        })
    }
}

// 获取微信群成员列表
export const getAsMemberList = ({asNo, page, pageSize}) => {
    return commonRequestData({
        apiName: 'GetGroupUserItem',
        requestData: {
            GroupNo: asNo,
            Page: page,
            PageSize: pageSize,
        }
    })
}

// 获取业务名片信息
export const getBusCardInfo = ({type = 0, page = 1, pageSize = 20, keyWord = ''}) => {
    return commonRequestData({
        apiName: 'GetBusinessTemplate',
        requestData: {
            TplType: type,
            Page: page,
            PageSize: pageSize,
            KeyWord: keyWord
        }
    })
}

// 设置用户名片默认模板
export const setBusCardTemp = (requestData) => {
    return commonRequestData({
        apiName: 'SetDefaultUserBusinessTemplate',
        requestData: {
            TplNo: requestData.TplNo,
            SetType: requestData.SetType,
            ViewProject: requestData.ViewProject,
            DefaultTxt: requestData.DefaultTxt,
        }
    })
}

// 执行更新微信群业务信息列表
export const updateWechatGroInfoList = ({ callback, groupWxId, kfWxId }) => {
    console.log('updateWechatGroInfoList')
    if (groupWxId && kfWxId) {
        // loadingVantToa({
        //     message: '系统正在更新此微信群的业务信息列表，可能需要几分钟或更长时间'
        // })
        loadingVantToa({})
        commonRequestData({
            apiName: 'UpdateWechatListItem',
            requestData: {
                GroupWxId: groupWxId,
                KfWxId: kfWxId
            }
        })
        .then(res => {
            console.log('执行更新微信群业务信息列表 res：', res)
            if (res.errcode == 0) {
                failTextVantToa('系统正在更新此微信群的业务信息列表，可能需要几分钟或更长时间')
                typeof callback === 'function' && callback()
            } else {
                if (res.errcode != -2 && res.errCode != 1100) {
                    failTextVantToa()
                } else {
                    clearVantToa()
                }
            }
        }, res => {
            console.log('fail: res', res)
            if (res.errcode != 2000) {
                failTextVantToa()
            }
        })
        .catch(res => {
            console.log('catch：res', res)
            failTextVantToa()
        })
    }
}

// 执行点赞
export const toParise = ({
    sourceNo,
    fromId,
    source,
    callback,
}) => {
    let data = false;
    if (sourceNo && source && fromId) {
        const ticket = getCookie('Ticket')
        if (isLoginChose(ticket)) {
            loadingVantToa({})
            post({
                url: '/api/v1/Praise',
                params: {
                    Ticket: ticket,
                    From_Id: Number(fromId),
                    SourceNo: sourceNo,
                    Source: source
                }
            })
            .then(res => {
                console.log("点赞 res：", res)
                if (res.errcode == 1000) {
                    data = res.data
                    clearVantToa()
                } else {
                    failTextVantToa(res.message)
                }
            }, res => {
                console.log("fail: res", res)
                if (res.errcode != 2000) {
                    failTextVantToa("服务器正在修整，请稍后")
                }
            })
            .catch(res => {
                console.log("catch：res", res)
                failTextVantToa("服务器正在修整，请稍后")
            })
            .finally(() => {
                typeof callback && callback(data)
            })
        }
    } else {
        typeof callback && callback(data)
    }
}

// 图片上传至服务器
export const imgUpLoadServers = ({

})

// 获取绑定微信信息
export const getBindWechatInfo = (callback) => {
    loadingVantToa({})
    let data = false
    commonRequestData({
        apiName: 'BindUserWx',
        requestData: ''
    })
    .then(res => {
        console.log('获取绑定微信信息 res：', res)
        if (res.errcode == 0) {
            clearVantToa()
            data = res.data
        } else {
            if (res.errcode != -2 && res.errCode != 1100) {
                failTextVantToa()
            } else {
                clearVantToa()
            }
        }
    }, res => {
        console.log('获取绑定微信信息fail: res', res)
        if (res.errcode != 2000) {
            failTextVantToa()
        }
    })
    .catch(res => {
        console.log('获取绑定微信信息catch：res', res)
        failTextVantToa()
    })
    .finally(() => {
        typeof callback === 'function' && callback(data)
    })
}

// 保存访问日志
export const saveLogVisit = ({
    referrer = '', // 访问上一个URL地址
    location = '', // URL地址
    addRess = '', // 位置地址
}) => {
    const requestData = getLog({
        referrer,
        location,
        addRess
    })
    commonRequestData({
        apiName: 'SetWebLog',
        requestData,
    })
    .then(res => {
        console.log('保存访问日志 res：', res)
    }, res => {
        console.log('保存访问日志fail: res', res)
    })
    .catch(res => {
        console.log('保存访问日志catch：res', res)
    })
}

// 获取用户信息
export const getUserInfo = () => {
    const userId = getCookie('UserId')
    if(isLoginChose(userId)){
        return commonRequestData({
            apiName: 'MyUserBasicInfo',
            // requestData: ''
        })
    }
}

// 获取账户信息
export const getUserAmount = () => {
    const ticket = getCookie('Ticket')
    if(isLoginChose(ticket)){
        const requestData = {
            Ticket: ticket,
            ApiKey: 'All',
            ApiOuterName: 'getUserAmount',
            RequestBody: '',
            TimeCut: new Date().getTime(),
            Nonce_Str: md5(String(random(0, 3000))),
        }
        const key = 'Ticket=' + ticket + '&Nonce_Str=' + requestData.Nonce_Str + '&TimeCut=' + requestData.TimeCut + '&signKey=' + process.env.SIGN_KEY
        requestData.Sign = md5(key).toUpperCase()
        return post({
            url: `api/v1/getUserAmount`,
            params: requestData,
            taskId: 'getUserAmoun',
            contentType: 'application/x-www-form-urlencoded'
        })
    }
}

// 获取用户安全系数
export const checkSecurity = (callback) => {
    if (typeof callback === 'function') {
        // callback(0)
        get({
            url: 'CheckSecurity',
            params: {
                UserId: getCookie('UserId')
            }
        })
        .then(res => {
            // console.log("获取用户安全系数 res：", res)
            if (res.errcode == 1000) {
                callback(res.data)
            }
        }, res => {
            console.log("fail: res", res)
            if (res.errcode != 2000) {
                // failTextVantToa("服务器正在修整，请稍后")
            }
        })
        .catch(res => {
            console.log("catch：res", res)
            // failTextVantToa("服务器正在修整，请稍后")
        })
    }
}

// 查看微信
export const checkWechatInfo = (requestData) => {
    return commonRequestData({
        apiName: 'UserIndex_MyWeChat',
        requestData: requestData,
        taskId: 'UserIndex_MyWeChat'
    })
}

// 获取个人主页-社群
export const getAsUserIndex = (requestData, taskId = 'UserIndex_MyWeChat') => {
    return commonRequestData({
        apiName: 'UserIndex_Society',
        requestData,
        taskId,
    })
}

// 获取个人主页-主讲
export const getWorkshopUserIndex = (requestData) => {
    return commonRequestData({
        apiName: 'UserIndex_Seminar',
        requestData,
        taskId: 'UserIndex_Seminar'
    })
}

// 获取用户设置信息
export const getUserSet = () => {
    return commonRequestData({
        apiName: 'UserBasicInfo',
        requestData: '',
    })
}

// 上传图片至服务器
export const upLoadImg = ({
    file, fileName, callback, headers = {
        "Content-Type": "multipart/form-data" 
    }
}) => {
    const formData = new FormData();
    formData.append('imgData', dataURLtoBlob(file), fileName)
    if (typeof callback === 'function') {
        let file = null
        loadingVantToa({})
        post({
            url: 'ImgUploadFromData',
            params: formData,
            headers,
        })
        .then(res => {
            console.log("上传图片至服务器 res：", res)
            if (res.errcode == 1000) {
                clearVantToa()
                file = res.data[0].FileUrl
            } else {
                failTextVantToa(res.message)
            }
        }, res => {
            console.log("fail: res", res)
            if (res.errcode != 2000) {
                failTextVantToa("服务器正在修整，请稍后")
            }
        })
        .catch(res => {
            console.log("catch：res", res)
            failTextVantToa("服务器正在修整，请稍后")
        })
        .finally(() => {
            typeof callback === 'function' && callback(file)
        })
    } else {
        return post({
            url: 'ImgUploadFromData',
            params: formData,
            headers,
        })
    }
}

// 上传用户头像
export const changHeadImg = (url) => {
    return post({
        url: 'EditHeadImg',
        params: {
            HeadImg: url
        }
    })
}

// 保存签名
export const saveSignature = ({
    signature = '', 
    callback,
    maxLength = 12,
}) => {
    if (isLoginChose()) {
        signature = getText(signature)
        if (signature.length > maxLength) {
            failTextVantToa(`签名不能超过${maxLength}字`)
            return false
        }
        loadingVantToa({})
        let isSuccess = false
        post({
            url: 'SetSignature',
            params: {
                Signature: signature
            },
            headers: {
                Version: 'V2'
            }
        })
        .then(res => {
            console.log("保存签名 res：", res)
            if (res.errcode == 1000) {
                failTextVantToa('保存成功')
                isSuccess = true
            } else {
                failTextVantToa(res.message)
            }
        }, res => {
            console.log("fail: res", res)
            if (res.errcode != 2000) {
                failTextVantToa("服务器正在修整，请稍后")
            }
        })
        .catch(res => {
            console.log("catch：res", res)
            failTextVantToa("服务器正在修整，请稍后")
        })
        .finally(() => {
            typeof callback === 'function' && callback(isSuccess)
        })
    }
}

// 获取帮助绑定微信信息
export const getBindWechatInfoHelp = (callback) => {
    if (typeof callback === 'function') {
        loadingVantToa({})
        let data = false
        commonRequestData({
            apiName: 'BindUserWx',
            requestData: '',
        })
        .then(res => {
            console.log("获取帮助绑定微信信息 res：", res)
            if (res.errcode == 1000) {
                data = res.data
            } else {
                failTextVantToa("服务器正在修整，请稍后")
            }
        }, res => {
            console.log("fail: res", res)
            if (res.errcode != 2000) {
                failTextVantToa("服务器正在修整，请稍后")
            }
        })
        .catch(res => {
            console.log("catch：res", res)
            failTextVantToa("服务器正在修整，请稍后")
        })
        .finally(() => {
            typeof callback === 'function' && callback(data)
        })
    }
}

// 获取个人，微信群列表
export const getUserWechatGroList = ({
    page,
    pageSize,
    userId,
}) => {
    return commonRequestData({
        apiName: 'UserIndex_WxSociety',
        requestData: {
            UserId: userId,
            Page: page,
            PageSize: pageSize,
        },
        taskId: `${page}${pageSize}UserIndex_WxSociety`
    })
}

// 获取所有主营产品
export const getProductList = (callback) => {
    let data = false
    get({
        url: 'api/v1/getGoodsItem',
        taskId: 'getGoodsItem',
    })
    .then(res => {
        console.log("获取所有主营产品 res：", res)
        if (res.errcode == 1000) {
            data = res.data
        }
    }, res => {
        console.log("fail: res", res)
    })
    .catch(res => {
        console.log("catch：res", res)
    })
    .finally(() => {
        typeof callback === 'function' && callback(data)
    })
}

// 获取当前网站版本号
export const getWebVersion = (callback) => {
    if (typeof callback === 'function') {
        get({
            url: 'GetWebConfig/Version'
        })
        .then(res => {
            console.log("获取当前网站版本号 res：", res)
            if (res.errcode == 1000) {
                callback(res.data)
            }
        }, res => {
            console.log("获取当前网站版本号fail: res", res)
        })
        .catch(res => {
            console.log("获取当前网站版本号catch：res", res)
        })
    }
}

// 获取名片范例
export const getBusCardExample = (callback) => {
    if (typeof callback === 'function') {
        loadingVantToa({})
        let data = false
        commonRequestData({
            apiName: 'UserCardExample'
        })
        .then(res => {
            console.log("获取名片范例 res：", res)
            if (res.errcode == 0) {
                clearVantToa()
                data = res.data
            } else {
                failTextVantToa("服务器正在修整，请稍后")
            }
        }, res => {
            console.log("fail: res", res)
            if (res.errcode != 2000) {
                failTextVantToa("服务器正在修整，请稍后")
            }
        })
        .catch(res => {
            console.log("catch：res", res)
            failTextVantToa("服务器正在修整，请稍后")
        })
        .finally(() => {
            typeof callback === 'function' && callback(data)
        })
    }
}

// 首次保存我的业务信息
export const saveUserBusiness = (requestData, callback) => {
    if (requestData && typeof callback === 'function') {
        loadingVantToa({})
        let data = false
        commonRequestData({
            apiName: 'AddUserBusiness',
            requestData,
            taskId: 'AddUserBusiness'
        })
        .then(res => {
            console.log("首次保存我的业务信息 res：", res)
            if (res.errcode == 0) {
                clearVantToa()
                data = true
            } else {
                failTextVantToa("服务器正在修整，请稍后")
            }
        }, res => {
            console.log("fail: res", res)
            if (res.errcode != 2000) {
                failTextVantToa("服务器正在修整，请稍后")
            }
        })
        .catch(res => {
            console.log("catch：res", res)
            failTextVantToa("服务器正在修整，请稍后")
        })
        .finally(() => {
            callback(data)
        })
    }
}